<?php
/**
 * BootAdmin is committed to providing solutions for quickly building web applications
 * Please view the LICENSE file that was distributed with this source code,
 * For the full copyright and license information.
 * Thank you very much for using BootAdmin.
 *
 * @Author G.r<root@BootAdmin.com>
 */

declare (strict_types=1);

namespace app\common\model;

use think\model\concern\SoftDelete;

/**
 * 用户模型
 */
class User extends BaseModel
{
    use SoftDelete;

    protected array $allowModifyFields = ['avatar', 'status'];

    protected array $fields = ['id', 'id' => 'value', 'username' => 'label'];

    /**
     * 关联用户组
     */
    public function group()
    {
        return $this->belongsTo(UserGroup::class, 'group_id');
    }

    /**
     * 密码加密
     * @param $value
     * @return string
     */
    public function setPasswordAttr($value): string
    {
        return password_hash($value, PASSWORD_DEFAULT);
    }

    /**
     * 验证密码
     * @param $password
     * @param $hash
     * @return bool
     */
    public static function passwordVerify($password, $hash) : bool
    {
        return password_verify($password, $hash);
    }

    /**
     * 搜索器 - id
     * @param $query
     * @param $value
     * @param $data
     */
    public function searchIdAttr($query, $value, $data)
    {
        $query->where('id','=', $value);
    }

    /**
     * 搜索器 - 用户名
     * @param $query
     * @param $value
     * @param $data
     */
    public function searchUsernameAttr($query, $value, $data)
    {
        $query->where('username','like', '%' . $value . '%');
    }

    /**
     * 搜索器 - 昵称
     * @param $query
     * @param $value
     * @param $data
     */
    public function searchNicknameAttr($query, $value, $data)
    {
        $query->where('nickname','like', '%' . $value . '%');
    }

    /**
     * 搜索器 - 手机号
     * @param $query
     * @param $value
     * @param $data
     */
    public function searchMobileAttr($query, $value, $data)
    {
        $query->where('mobile','=', $value);
    }

    /**
     * 搜索器 - 邮箱
     * @param $query
     * @param $value
     * @param $data
     */
    public function searchEmailAttr($query, $value, $data)
    {
        $query->where('email','=', $value);
    }

    /**
     * 搜索器 - 状态
     * @param $query
     * @param $value
     * @param $data
     */
    public function searchStatusAttr($query, $value, $data)
    {
        $query->where('status','=', $value);
    }

    /**
     * 搜索器 - 创建时间
     * @param $query
     * @param $value
     * @param $data
     */
    public function searchCreateTimeAttr($query, $value, $data)
    {
        $query->whereBetweenTime('create_time', $value[0], $value[1]);
    }
}